<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 16:45:18
 * Info: 管理员管理
 */

namespace app\admin\controller;

use app\common\model\Admin as AdminModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use think\facade\View;

class Admin extends Base
{

    /**
     * 管理员列表
     */
    public function index()
    {
        //获取角色组的名字和id
        $role_group_name = AuthGroupModel::getRoleGroup();
        $params          = [];
        //判断是否是ajax发送方式
        if ($this->request->isAjax()) {
            $params['limit'] = (int)input('limit', 10);
            $params['page']  = (int)input('page', 1);
            $params['first'] = ($params['page'] - 1) * $params['limit'];
            $params['field'] = input('field', 'id');
            $params['order'] = input('order', 'asc');
            $params['key']   = input('key');
            $data            = AdminModel::getAdminList($params);
            $this->success('ok', $data['list'], $data['count']);
        }

        View::assign('role_group_name', $role_group_name);

        return View::fetch();
    }

    /**
     * 添加管理员
     * @return mixed|\support\Response|\think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->input();
            if (empty($param['username'])) {
                $this->error('用户名不能为空');
            }
            if (empty($param['password'])) {
                $this->error('密码不能为空');
            }
            if (empty($param['auth_ids'])) {
                $this->error('请选择角色组哦');
            }

            //生成随机盐
            $salt              = substr(uniqid(), 6, 6);
            $param['salt']     = $salt;
            $param['password'] = cmf_password($param['password'], $salt);

            //判断用户名是否存在
            $isUser = AdminModel::where('username', $param['username'])->count();
            if ($isUser) {
                $this->error('该用户名已存在哦');
            }

            $authIds = ! empty($param['auth_ids']) ? $param['auth_ids'] : [];
            unset($param['auth_ids']);

            $param['create_time'] = time();
            $param['update_time'] = time();

            $resId = AdminModel::strict(false)->insertGetId($param);
            //保存用户的角色组
            AuthGroupAccessModel::updateGroupAccess($resId, $authIds);
            $this->success('操作成功');
        }
        $roleGroupName = AuthGroupModel::getRoleGroup();
        View::assign('role_group_name', $roleGroupName);

        return View::fetch();
    }

    /**
     * 编辑管理员
     * @return mixed|\support\Response|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            //获取序列化数据
            $param = self::input();
            if (empty($param['id'])) {
                $this->error('参数错误');
            }

            //修改密码
            if ( ! empty($param['password'])) {
                $salt              = substr(uniqid(), 6, 6);
                $param['salt']     = $salt;
                $param['password'] = cmf_password($param['password'], $salt);
            } else {
                unset($param['password']);
            }
            $type = ! empty($param['type']) ? $param['type'] : '';
            //保存角色组，编辑个人信息的时候不处理用户组
            $authIds = ! empty($param['auth_ids']) ? $param['auth_ids'] : [];
            AuthGroupAccessModel::updateGroupAccess($param['id'], $authIds, $type);
            unset($param['auth_ids']);

            AdminModel::update($param, ['id' => $param['id']]);
            $this->success('操作成功');
        }
        $id              = input('get.id');
        $roleGroupName   = AuthGroupModel::getRoleGroup();
        $data            = AdminModel::find($id);
        $authGroupAccess = AuthGroupAccessModel::where('uid', $id)->column('group_id');

        View::assign('data', $data);
        View::assign('group_access', $authGroupAccess);
        View::assign('role_group_name', $roleGroupName);

        return View::fetch();
    }

    /**
     * 删除管理员
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            if ($id == 1) {
                $this->error("不允许删除id为1的数据哦");
            }
            AdminModel::where(['id' => $id])->delete();
            //删除角色组
            AuthGroupAccessModel::updateGroupAccess($id, []);

            $this->success("删除成功");
        }

    }

    /**
     * 管理员列表页的按钮操作
     * @return void
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            if ($id == 1) {
                $this->error("不允许删除id为1的数据哦");
            }
            $field = input('field');
            $val   = input('val');
            AdminModel::update([$field => $val], ['id' => $id]);
            $this->success('操作成功');
        }

    }

    /**
     * 获取基本资料
     * @return void
     */
    public function adminInfo()
    {
        $id   = (int)input('get.id');
        $data = AdminModel::find($id);
        View::assign('data', $data);

        return View::fetch('user_info');
    }

    /**
     * 修改密码
     * @return void
     */
    public function adminPass()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $rule  = [
                'id|id'            => 'require',
                'oldpwd|旧密码'    => 'require',
                'newpwd|新密码'    => 'require',
                'confirm|确认密码' => 'require'
            ];
            $this->validate($param, $rule);
            if ($param['newpwd'] != $param['confirm']) {
                $this->error('两次密码输入不一致');
            }
            //查询旧密码是否正确
            $salt     = substr(uniqid(), 6, 6);
            $findInfo = AdminModel::where('id', $param['id'])->field('password,salt')->find()->toArray();
            $oldPwd   = cmf_password($param['oldpwd'], $findInfo['salt']);
            if ($oldPwd != $findInfo['password']) {
                $this->error('旧密码不正确哦');
            }
            $data = [
                'password' => cmf_password($param['newpwd'], $salt),
                'salt'     => $salt
            ];
            AdminModel::update($data, ['id' => $param['id']]);
            $this->success('操作成功');
        }
        $id = cmf_get_admin_id();
        View::assign('id', $id);

        return View::fetch('user_pass');
    }
}
